import 'dart:async';

import 'package:baidu_map/utils/log_util.dart';
import 'package:baidu_map/utils/map_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';

class SingleLocationWithoutMapPage extends StatefulWidget {
  const SingleLocationWithoutMapPage({super.key});

  @override
  State<SingleLocationWithoutMapPage> createState() => _SingleLocationWithoutMapPageState();
}

class _SingleLocationWithoutMapPageState extends State<SingleLocationWithoutMapPage> {

  BaiduLocation? _locationResult;

  StreamSubscription? _listener;

  @override
  void initState() {
    super.initState();


    _listener = MapUtils().propertyListener?.onChanged.listen((newValue) {
      setState(() {
        _locationResult = newValue;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _listener?.cancel();
  }


  final GlobalKey _buttonKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    List<Widget> resultWidgets = [];
    if (_locationResult?.locTime != null) {
      _locationResult?.getMap().forEach((key, value) {
        resultWidgets.add(_resultWidget(key, value));
      });
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text('单次定位(无地图)'),
      ),
      body: Column(
        children: [
          Container(
            color: Colors.blue[100],
            child: SizedBox(
              height: MediaQuery.of(context).size.height - 81 - 48,
              child: ListView(
                children: resultWidgets,
              ),
            ),
          ),
          ElevatedButton(
            key: _buttonKey,
            onPressed: () {
              ///设置定位参数
              MapUtils().startLocation();

              LogUtil.d('ElevatedButton的高度是${_buttonKey.currentContext?.size}');
            },
            child: const Text('开始定位')
          )
        ],
      ),
    );
  }

  Widget _resultWidget(key, value) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('$key: ' '$value')
        ],
      ),
    );
  }
}